<template>
    <!-- 确认订单选择地址 -->
    <van-address-list
        v-if="action == 'select'"
        v-model="active"
        :list="list"
        default-tag-text="默认"
        @add="AddressAdd"
        @edit="AddressEdit"
        @select="CartSelect"
    />
    <!-- 从会员中心点击收货地址 -->
    <van-address-list
        v-else
        v-model="active"
        :list="list"
        default-tag-text="默认"
        @add="AddressAdd"
        @edit="AddressEdit"
        @select="AddressSelect"
    />
</template>

<script setup>
    const { proxy } = getCurrentInstance()

    // 接收关键词参数
    var query = proxy.$route.query.action ? proxy.$route.query.action : '';
    let action = ref(query)

    // 收货地址列表
    let list = reactive([])
    let active = ref(0) //标识 是否是默认地址

    // 当页面一加载进来的时候就会触发挂载前的生命周期钩子函数
    onBeforeMount(() => {
        AddressList()
    })

    const AddressList = async () => {
        // 发起请求
        var result = await proxy.$POST({
            url: '/address/index',
            params: {
                busid:proxy.$business.value.id
            }
        })

        // 要么是出错 要么没出错
        if (result.code == 0) {
            proxy.$fail(result.msg)
            return false
        }

        result.data.map((item) => {
            // 找出默认地址
            if (item.status == "1") active .value = item.id

            // 重组收货地址的结构
            list.push({
                id: item.id,
                name: item.consignee,
                tel: item.mobile,
                address: `${item.region_text} ${item.address}`,
                isDefault:item.status == '1' ? true : false
            })
        })
    }

    // 收货地址添加
    const AddressAdd = async () => proxy.$router.push('/address/add')

    //收货地址的编辑
    const AddressEdit = async (item) => proxy.$router.push({path:'/address/edit',query:{id:item.id}})

    // 切换默认的收货地址
    const AddressSelect = async (item,index) => {
        var result = await proxy.$POST({
            url: '/address/check',
            params: {
                busid: proxy.$business.value.id,
                id:item.id
            }
        })

        if (result.code == 0) {
            proxy.$fail(result.msg)
            return false
        }

        // 成功就修改默认的状态
        list.map(value => {
            // 把所有的地址全部修改为默认地址
            value.isDefault = false

            //刚刚切换的地址 设置为默认
            if(value.id == item.id) value.isDefault = true
        })

    }

    // 确认订单切换地址
    const CartSelect = async (item, index) =>{
        item.region_text = item.address

        // 将选择的收货地址存入到cookie中
        proxy.$cookies.set('address', item)

        proxy.$router.go(-1)
    }

</script>
